//
//  GDNetworkTool.swift
//  weibo
//
//  Created by user on 15/11/24.
//  Copyright © 2015年 user. All rights reserved.
//

import UIKit

import AFNetworking


//网络请求的枚举
enum GDNetoworkMethod: String {
    case GET = "GET"
    case POST = "POST"
}


///统一管理错误
enum GDNetworkToolError: Int {
    case EmptyAccessToken = -1
    case EmptyUid = -2
    
    //属性，根据不同的枚举类型返回不同的值
    var description: String {
        switch self {
        case .EmptyAccessToken:
            return "AccessToken没有值"
        case .EmptyUid:
            return "Uid没有值"
        }
    }
    
    //方法，根据当前类型返回一个NSError
    func error() -> NSError {
        return NSError(domain: "cn.itcast.error.net", code: self.rawValue, userInfo: ["description" : self.description])
    }
}



//网络单例

class GDNetworkTool: AFHTTPSessionManager {

    //单例
    static let sharedInstance: GDNetworkTool = {
        let baseURL = NSURL(string: "https://api.weibo.com/")
        let tool = GDNetworkTool(baseURL: baseURL)
        
        tool.responseSerializer.acceptableContentTypes?.insert("text/plain")
        
        return tool
    }()
    
    /// 申请应用时分配的AppKey
    private let client_id = "2741137523"
//    private let client_id = "173700330"
    
    /// 申请应用时分配的AppSecret
    private let client_secret = "524b9a954497bb9b7d345f5124ef5b36"
//    private let client_secret = "696426f35e8cadf118ba783376857b4d"
    
    /// 授权回调地址, 一定要一模一样
    let redirect_uri = "http://www.baidu.com/"
    
    
    func oauthURL() -> NSURL {
        
        // GET方式拼接登录界面请求地址
        let urlString = "https://api.weibo.com/oauth2/access_token?client_id=\(client_id)&redirect_uri=\(redirect_uri)"
        return NSURL(string: urlString)!
        
    }
    
    // MARK: - 网络工具类加载AccessToken, 只负责加载数据,让别人来处理数据(通过闭包)
    func loadAccessToken(code: String, finished: (result: [String: AnyObject]?, error: NSError?) -> ()) {
        // url地址
        let urlString = "https://api.weibo.com/oauth2/access_token"
        
        // 请求参数
        let parameters = [
            "client_id": client_id,
            "client_secret": client_secret,
            "grant_type": "authorization_code",
            "code": code,
            "redirect_uri": redirect_uri
        ]
        
        //发送POST请求
        request(requestMethod: GDNetoworkMethod.POST, urlString: urlString, parameters: parameters, needAccessToken: false, finished: finished)
        
//        // 发送POST请求
//        POST(urlString, parameters: parameters, success: { (_, result) -> Void in
//            //            print("result: \(result)")
//            // as! 强制转换,f 有风险,如果转换不了,直接崩溃
//            // as? 如果能转成功就转换,如果不能转换就返回nil
//            finished(result: result as? [String : AnyObject], error: nil)
//            }) { (_, error) -> Void in
//                //                print("error:\(error)")
//                finished(result: nil, error: error)
//        }
    }
    
    //获取用户数据
    func loadUserInfo(finished: (result: [String: AnyObject]?, error: NSError?) -> ()){
        
//        guard let access_token = GDUserAccount.loadUserAccount()?.access_token else {
//            // 能到这里面来表示access_token 没有值
//            print("access_token没有值")
//            
//            let error = GDNetworkToolError.EmptyAccessToken.error()
//            
//            finished(result: nil, error: error)
//            
//            
//            return
//        }
        //测试Uid为空
//        GDUserAccount.loadUserAccount()?.uid = nil
        
        guard let uid = GDUserAccount.loadUserAccount()?.uid else {
            //能到这里来表示uid没有值
//            print("uid没有值")
            
            let error = GDNetworkToolError.EmptyUid.error()
            finished(result: nil, error: error)
            return
            
        }
        let urlString = "2/users/show.json"
        
        //参数
        let parameters = [
//            "access_token": access_token,
            "uid": uid
        ]
        
        //发送请求 网络工具类只负责加载数据，不处理数据，交给别人处理
        request(requestMethod: GDNetoworkMethod.GET, urlString: urlString, parameters: parameters, needAccessToken: true, finished: finished)
        
        
        
//        GET(urlString, parameters: parameters, success: { (_, result) -> Void in finished(result: result as? [String: AnyObject], error: nil)
////            print("加载数据\(result)")
//            }){ (_, error) -> Void in
//                finished(result: nil, error: error)
//        }
    }
    
    //加载微博数据
    func loadStatus(finished: NetworkCallback) {
        
        //url
        let urlString = "https://api.weibo.com/2/statuses/home_timeline.json"
        //参数
        let parameters = [String: AnyObject]()
        
        //调用封装好的GET请求
        let debug = false
        if debug {
            //调试，加载本地数据
            loadLocalStatuses(finished)
        }else{
            //不是调试，加载网络微博数据
            request(requestMethod: GDNetoworkMethod.GET, urlString: urlString, parameters: parameters, needAccessToken: true, finished: finished)
        }
        
    }
    
    
    //将本地的测试微博数据加载进来
    private func loadLocalStatuses(finished: NetworkCallback){
        //获取测试微博数据的路径
        let path = NSBundle.mainBundle().pathForResource("statyses", ofType: "json")!
        
        //从文件加载数据 NSData
        let data = NSData(contentsOfFile: path)!
        
        // 将 NSData 转成 JSON
        // throws 有异常,需要处理异常
        // try! 强制try, 如果JSONObjectWithData出现异常,程序直接崩溃
        //        let json = try! NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions(rawValue: 0))
        
        do {
            let json = try? NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions(rawValue: 0))
            
            // 通知调用者获取到了本地数据
            finished(result: json as? [String: AnyObject], error: nil)
        } catch {
            print("出现了异常")
        }
    }
    
    
    //定义类型别名
    typealias NetworkCallback = (result: [String: AnyObject]?, error: NSError?) -> ()
    
    
    //抽取AFN GET / POST 方法，网络请求的统一入口都是这个方法
    func request(requestMethod requestMethod: GDNetoworkMethod, urlString: String, var parameters:[String: AnyObject], needAccessToken: Bool, finished: NetworkCallback) {
        //需要accessToken，就拼接
        if needAccessToken {
            guard let access_token = GDUserAccount.loadUserAccount()?.access_token else{
                let error = GDNetworkToolError.EmptyAccessToken.error()
                
                finished(result: nil, error: error)
                return
            }
            
            //在参数里面拼接 access_token
            parameters["access_token"] = access_token
        }
        
        // 准备成功的闭包, 在外面只要准备一次,可以传给GET,也可以传给POST
        let successCallback = { (task: NSURLSessionDataTask, result: AnyObject) -> Void in
            //执行的代码
            finished(result: result as? [String : AnyObject], error: nil)
        }
        
        // 准备失败的闭包
        let failureCallback = { (task: NSURLSessionDataTask?, error: NSError) -> Void in
            finished(result: nil, error: error)
        }
        
        //根据请求方式，发送对应的请求
        switch requestMethod {
        case .GET:
            GET(urlString, parameters: parameters, success: successCallback, failure: failureCallback)
        case .POST:
            POST(urlString, parameters: parameters, success: successCallback, failure: failureCallback)
        }
    }
    
}
